package com.zh.system.utils;

import com.zh.system.config.MinioConfig;
import com.zh.system.domain.tmp.UpLoadChunkTmp;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.DeleteResult;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@Component
@Data
@Slf4j
@RequiredArgsConstructor
public class MinioUtil {

    private final MinioClient client;
    private final MinioConfig config;

    /**
     * 创建存储桶
     *
     * @param bucketName 存储桶名称
     */
    public void createBucket(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        if (!client.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    public void upLoadChunk(UpLoadChunkTmp upLoadChunkTmp) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        // 上传文件流
        client.putObject(PutObjectArgs
                .builder()
                .bucket(upLoadChunkTmp.getBucketName())
                .object(upLoadChunkTmp.getObjectName())
                .stream(upLoadChunkTmp.getStream(), upLoadChunkTmp.getChunkSize(), -1).build());
        upLoadChunkTmp.getStream().close();
    }

    public void composeChunk(String bucketName, String objectName, List<ComposeSource> sources) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        client.composeObject(
                ComposeObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .sources(sources)
                        .build()
        );
    }

    public void deleteChunk(String bucketName, List<DeleteObject> deleteObjects, String fileName) {
        try {
            Iterable<Result<DeleteError>> results = client
                    .removeObjects(RemoveObjectsArgs.builder()
                            .bucket(bucketName)
                            .objects(deleteObjects)
                            .build());
            for (Result<DeleteError> result : results) {
                DeleteError deleteError = result.get();
                log.error("error in deleteing object" + deleteError.objectName() + ";" + deleteError.message());
            }
            log.info("删除{}所有分片成功!", fileName);
        } catch (Exception e) {
            log.error("minio删除文件失败{}", e.getMessage(), e);
        }
    }

    public void deleteObject(String bucketName, String objectName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        client.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }

    /**
     * 获取文件地址
     *
     * @param bucketName bucketName bucket名称 lawsweep
     * @param objectName objectName 文件全名称 2024116/1.jpg
     * @return
     */
    public String getUrl(String bucketName, String objectName) {
//        return client.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
//                .method(Method.GET)
//                .bucket(bucketName)
//                .object(objectName)
//                .build());
        return config.getEndpoint() + "/" + bucketName + "/" + objectName;
    }
}
